<template>
  <el-card>
    <div class="btn">
      <el-button type="primary" @click="dialogVisible = true, isAdd = true"
        ><i class="el-icon-plus"></i> 新增</el-button
      >
      <el-button type="success" @click="handleAdministrator"  :disabled="multipleSelection.length == 0 || multipleSelection.length > 1"
        ><i class="el-icon-edit"></i> 修改</el-button
      >
      <el-button type="danger" :disabled="multipleSelection.length == 0" @click="deleteAdministrator"
        ><i class="el-icon-delete"></i> 删除</el-button
      >
    </div>
    <el-table
    :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
    <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="index" width="50" label="编号"> </el-table-column>
      <el-table-column prop="username" label="用户名"> </el-table-column>
      <el-table-column label="用户头像">
        <template slot-scope="data">
          <el-avatar :src="data.row.img" shape="circle"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="注册时间"></el-table-column>
      <el-table-column prop="jurisdictionName" label="角色"> </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="[5, 10, 15]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <el-dialog
      title='新增超级管理员'
      :visible.sync="dialogVisible"
      width="70%"
      :before-close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="头像上传" prop="img">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.img" :src="form.img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        是否添加为超级管理员
        <el-switch style="margin-left: 1vw;"
          v-model="form.jurisdiction"
          active-color="#409eff"
          inactive-color="#ccc"
        ></el-switch>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addAdministrator"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title='修改超级管理员'
      :visible.sync="dialogVisible2"
      width="70%"
      :before-close="handleClose"
    >
      <el-form :model="changeForm" :rules="rules" ref="changeForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="changeForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="changeForm.password"></el-input>
        </el-form-item>
        <el-form-item label="头像上传" prop="img">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleChangeAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="changeForm.img" :src="changeForm.img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        是否添加为超级管理员
        <el-switch style="margin-left: 1vw;"
          v-model="changeForm.jurisdiction"
          active-color="#409eff"
          inactive-color="#ccc"
        ></el-switch>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="changeAdministrator"
          >确 定</el-button
        >
      </span>
    </el-dialog>
</el-card>
</template>

<script>
import { addAdministrator, changeAdministrator, deleteAdministrator, getAdministrator } from '@/api/administrator'

export default {
  data () {
    return {
      tableData: [],
      multipleSelection: [],
      form: {
        username: '',
        password: '',
        jurisdiction: false,
        img: ''
      },
      changeForm: {
        id: '',
        username: '',
        jurisdiction: false,
        password: '',
        img: ''
      },
      dialogVisible: false,
      dialogVisible2: false,
      isAdd: true,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ]
      },
      page: 1,
      pageSize: 10,
      total: 1,
      currentPage4: 1
    }
  },
  methods: {
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    handleAdministrator () {
      const selectedAdmin = JSON.parse(JSON.stringify(this.multipleSelection[0]))
      this.changeForm = {
        id: selectedAdmin.id,
        username: selectedAdmin.username,
        img: selectedAdmin.img || '',
        jurisdiction: selectedAdmin.jurisdictionName === '超级管理员',
        password: ''
      }
      this.dialogVisible2 = true
      this.isAdd = false
    },
    handleClose () {
      this.$confirm('关闭对话框，内容将消失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (this.isAdd) {
            this.form = {
              username: '',
              password: '',
              jurisdiction: false,
              img: ''
            }
            this.dialogVisible = false
          } else {
            this.dialogVisible2 = false
          }
        }).catch(() => {})
    },
    getAdministrator () {
      getAdministrator(this.page, this.pageSize).then(data => {
        this.tableData = data.data.rows
        this.total = data.data.total
        this.tableData.forEach(item => {
          item.createTime = item.createTime.split('T')[0] + ' ' + item.createTime.split('T')[1]
        })
        // this.total = data.total
      })
    },
    addAdministrator () {
      addAdministrator(this.form).then(data => {
        if (data.code === 1) {
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.dialogVisible = false
          this.getAdministrator()
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    changeAdministrator () {
      changeAdministrator(this.changeForm).then(data => {
        if (data.code === 1) {
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          this.dialogVisible2 = false
          this.getAdministrator()
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    deleteAdministrator () {
      const idList = this.multipleSelection.map(item => item.id)
      deleteAdministrator(idList).then(data => {
        if (data.code === 1) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getAdministrator()
        }
      })
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.getAdministrator()
    },
    handleCurrentChange (val) {
      this.page = val
      this.getAdministrator()
    },
    handleAvatarSuccess (res, file) {
      if (res.code === 1) {
        this.form.img = res.data
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    handleChangeAvatarSuccess (res, file) {
      if (res.code === 1) {
        this.changeForm.img = res.data
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    beforeAvatarUpload (file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是图片格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return true
    }
  },
  created () {
    this.getAdministrator()
  }
}
</script>

<style scoped>
.el-form > .el-form-item {
  width: 25vw;
  margin-right: 8vw;
}

.el-form {
  display: flex;
  flex-wrap: wrap;
}

.btn {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.btn .el-button {
  padding: 10px 20px;
  display: flex;
  align-items: center;
  gap: 6px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.btn .el-button i {
  font-size: 16px;
}

.btn .el-button:hover {
  transform: translateY(-2px);
}

.avatar-uploader {
  border: 2px dashed var(--border-color);
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  width: 128px;
  height: 128px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--background-color);
}

.avatar-uploader:hover {
  border-color: var(--primary-color);
  background-color: var(--hover-color);
}

.avatar-uploader-icon {
  font-size: 32px;
  color: var(--text-color-secondary);
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
  transition: all 0.3s;
}

.avatar-uploader:hover .avatar-uploader-icon {
  color: var(--primary-color);
  transform: scale(1.1);
}

.avatar {
  width: 128px;
  height: 128px;
  display: block;
  object-fit: cover;
  border-radius: 8px;
}

.el-dialog__body {
  padding: 30px !important;
}

.el-form-item {
  margin-bottom: 24px !important;
}

.el-form-item__label {
  font-weight: 500 !important;
  color: var(--text-color) !important;
}

.el-input__inner {
  border-radius: 6px !important;
}

.el-switch {
  margin-top: 8px !important;
}
</style>
